/**
 * @Description: localStorage，sessionStorage，cookie相关操作函数封装
 * @Autor: Yao
 * @Date: 2020-03-20 14:32:14
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-03-24 18:15:25
 * @module storage
 */

/**
 * @description 设置本地存储
 * @param {string} key 存储key
 * @param {*} value 存储值
 * @param {number} expire 有效期，单位小时，默认24, 0表示立即过期，-1表示不设置过期时间
 */
export function setLocal(key, value, expire = -1) {
  if (!value) {
    return localStorage.setItem(key, '')
  }
  let expireTime
  if (expire === -1) {
    expireTime = -1
  } else {
    expireTime = new Date().getTime() + expire * 60 * 60 * 1000
  }
  let data = {
    expireTime: expireTime,
    body: value,
  }
  localStorage.setItem(key, JSON.stringify(data))
}

/**
 * @description 获取本地存储,会判断过期时间，如果已过期返回空，否则返回存储的内容
 * @param {string} key 键名
 * @returns {*}
 */
export function getLocal(key) {
  const dataStr = localStorage.getItem(key)
  if (!dataStr) return
  try {
    const data = JSON.parse(dataStr)
    let { expireTime, body } = data
    if (expireTime === undefined) return data
    if (expireTime === -1) return body
    let now = new Date().getTime()
    if (now > expireTime) {
      localStorage.setItem(key, '') // 已过期，删除存储的值
      return
    }
    return body
  } catch (e) {
    return ''
  }
}

/**
 * @description 移除本地存储
 * @param {String} key  属性
 */
export function removeLocal(key) {
  localStorage.removeItem(key)
}

/**
 * @description  sessionStorage写入/改写数据
 * @param {string} key 键值，字符串
 * @param {*} val 内容
 */
export function setSession(key, val) {
  sessionStorage.setItem(key, JSON.stringify(val))
}

/**
 * @description  根据键的名称查询存储在sessionStorage的数据
 * @param {string} key 键的名称，字符串
 * @returns {*}
 */
export function getSession(key) {
  const dataStr = sessionStorage.getItem(key)
  if (!dataStr) return
  try {
    return JSON.parse(dataStr)
  } catch (e) {
    console.error(e)
  }
}

/**
 * @description 根据键的名称移除
 * @param {String} key  键名
 */
export function removeSession(key) {
  sessionStorage.removeItem(key)
}

/**
 * @description 设置cookie
 * @param {String} key  属性
 * @param {*} value  值
 * @param { String } expire  过期时间,单位天，默认一天
 */
export function setCookie(key, value, expire = 1) {
  const d = new Date()
  d.setDate(d.getDate() + expire)
  document.cookie = `${key}=${value};expires=${d.toUTCString()}`
}

/**
 * @description 通过键名cookie,无会返回空串
 * @param {String} key  属性
 * @returns {string}
 */
export function getCookie(key) {
  const cookieStr = unescape(document.cookie)
  const arr = cookieStr.split('; ')
  let cookieValue = ''
  for (let i = 0; i < arr.length; i++) {
    const temp = arr[i].split('=')
    if (temp[0] === key) {
      cookieValue = temp[1]
      break
    }
  }
  return cookieValue
}

/**
 * @description 根据键名移除cookie
 * @param {String} key  属性名
 */
export function removeCookie(key) {
  document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
}
